﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Web.Security;
using System.Net;
using System.Web.UI.HtmlControls;
using System.Web.Services;
using System.Web.Script.Services;

public partial class Account_Profile : System.Web.UI.Page
{
    protected UserTeam userTeam;
    protected GameweekTeam currentTeam;
    List<Player> lineup;
    List<Player> subs;
    static User user;
    static JsonParser jsonParser;
    protected UserLeague userLeague;
    public string password = "test";
    public string username = "test";

    protected void Page_Init(object sender, EventArgs e)
    {
        userTeam = new UserTeam();
        userLeague = new UserLeague();
        jsonParser = new JsonParser();
        currentTeam = jsonParser.getTeam("1", User.Identity.Name);
        userTeam.currentTeam = currentTeam;

        

        user = (User)Session["UserSession"];
        if (user != null)
        {
            password = user.password;
            username = user.username;


        
        }
        else
        {
            Response.Redirect("~/Account/Login.aspx");
        }



        lineup = new List<Player>();
        subs = new List<Player>();
        userTeam.currentTeam.initPositions();
        listPlayers();

        try
        {
            UserTeam team = jsonParser.getUserTeam(user.username);
            userTeam = team;
            UserLeague league = jsonParser.getLeague(user.username);
            
            if (user != null)
            {
                teamname.Text = (team.teamName);
            }

            getScore();
          
        }
        catch(NullReferenceException ex)
        {
            
        }
        catch(WebException ex)
        {
          
        }
        
    }
    private void getScore()
    {
        try
        {
            UserLeague league = jsonParser.getLeague(user.username);
            UserTeam team = jsonParser.getUserTeam(user.username);
            int counter = 0;
            foreach (UserTeam scorebyteam in league.teams)
            {
                counter++;
                
               if(scorebyteam.teamName.Equals(userTeam.teamName)){
                    leaguename.Text = team.leagueName + " ("+counter+"/"+league.teams.Count+")";
                }
                AddRow(counter, scorebyteam.teamName, scorebyteam.gameWeekScore, scorebyteam.leagueScore);
            }

        }
        catch (WebException ex)
        {
        }
        catch (NullReferenceException ex)
        {
        }
    }

    private void AddRow(int counter, string teamName, int gameweekScore, int totalScore)
    {
        TableRow newRow = new TableRow();
        TableCell pos = new TableCell();
        pos.Text = counter + ".";
        TableCell name = new TableCell();
        name.Text = teamName;
        TableCell gwScore = new TableCell();
        gwScore.Text = gameweekScore + "";
        TableCell totScore = new TableCell();
        totScore.Text = totalScore + "";

        totScore.CssClass = "last";

        newRow.Controls.Add(pos);
        newRow.Controls.Add(name);
        newRow.Controls.Add(gwScore);
        newRow.Controls.Add(totScore);
       

        if (counter % 2 == 0)
        {
            newRow.CssClass += "even";
        }
        else
        {
            newRow.CssClass += "odd";
        }

        if (teamName.Equals(userTeam.teamName))
        {
            newRow.CssClass += " you";
        }

        teamsTable.Controls.Add(newRow);
    }
    
    private void listPlayers()
    {
        if (userTeam.currentTeam != null)
        {
            displayPlayers(userTeam.currentTeam.keepers);
            displayPlayers(userTeam.currentTeam.defenders);
            displayPlayers(userTeam.currentTeam.midfielders);
            displayPlayers(userTeam.currentTeam.forwards);
        }
    }
       
    private void displayPlayers(IList<Player> players)
    {
        foreach (Player player in players)
        {
            Label myLabel = new Label();
            myLabel.Text = player.playerName;
            if (player.substitute == false)
            {
                //Checks position and displays players in correct row
                lineup.Add(player);
                HtmlGenericControl playerContainer = new HtmlGenericControl("div");
                playerContainer.InnerHtml = "<span>" + formatPlayerName(player.playerName) + "</span>";
                string cssClass = player.playerID.ToString();
                playerContainer.Attributes.Add("class", "player " + player.position.ToString() + " " + cssClass);

                switch (player.position)
                {
                    case Position.Keeper:
                        keeperRow.Controls.Add(playerContainer);
                        break;
                    case Position.Defender:
                        defRow.Controls.Add(playerContainer);
                        break;
                    case Position.Midfielder:
                        midRow.Controls.Add(playerContainer);
                        break;
                    case Position.Forward:
                        attRow.Controls.Add(playerContainer);
                        break;
                    default: 
                        break;
                }
            }
            else
            {
                // Displays substitutes on the bench
                subs.Add(player);
                HtmlGenericControl sub = new HtmlGenericControl("div");
                string cssClass = player.playerID.ToString();
                sub.Attributes.Add("class", "sub " + player.position.ToString() + " " + cssClass);
                sub.InnerHtml = "<span class='subPlayerName'>" + formatPlayerName(player.playerName) + "</span>";
                bench.Controls.Add(sub);
            }
        }
        Players.Controls.Add(new LiteralControl("<br />"));
        currentTeam.substitutes = subs;
    }


    private string formatPlayerName(string playerName)
    {
        string formattedName = "";
        string[] temp = playerName.Split(' ');
        if (temp.Length == 1)
        {
            return playerName;
        }
        else if (temp.Length == 2)
        {
            formattedName = temp[0].ElementAt(0) + "." + temp[1];
        }
        else if (temp.Length == 3)
        {
            formattedName = temp[1] + " " + temp[2];
        }
        return formattedName;
    }

    [WebMethod]
    [ScriptMethod]
    public static Boolean swapPlayers(string playerin, string playerout)
    {
        if (jsonParser != null && user != null)
        {
            return jsonParser.subPlayer(user.username, user.password, playerin, playerout);
        }
        else
        {
            return false;
        }
    }


}